﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using WPF_PathSearchUtil.service;
using WPF_PathSearchUtil.utils;

namespace WPF_PathSearchUtil.data_access
{
    public class BackendClient : CSVReadOrWrite
    {
        private HttpClient httpClient;

        /// <summary>
        /// 创建httpclient实例，定义 baseURL
        /// </summary>
        public BackendClient()
        {
            httpClient = new HttpClient();
            httpClient.BaseAddress = new Uri("http://localhost:8080/");
        }

        public Resp Read(params object[] items)
        {
            return DeliverParams (items);
        }

        public Resp Write(params object[] items)
        {
            return DeliverParams(items);
        }

        public Resp DeliverParams(params object[] items)
        {
            String url = null;
            HttpMethod httpMethod = null;
            Object data = null;
            foreach (object item in items)
            {
                if (item is string) { 
                    url = (String) item;
                    continue;
                }
                if (item is HttpMethod)
                {
                    httpMethod = (HttpMethod) item;
                    continue;
                }
                data = item;
            }
            return SendRequest(url,httpMethod,data);
        }

        /// <summary>
        ///     发送请求，获得响应数据
        /// </summary>
        /// <param name="url"></param>
        /// <param name="method"></param>
        /// <param name="data"></param>
        /// <returns></returns>
        public Resp SendRequest(String url, HttpMethod method, Object data)
        {
            try
            {
                //构造请求
                var request = new HttpRequestMessage(method, url);
                //post请求
                if (method.Method.Equals(HttpMethod.Post.Method, StringComparison.OrdinalIgnoreCase))
                {
                    //将要传递的数据转换为json字符串
                    var jsonData = JsonConvert.SerializeObject(data);
                    request.Content = new StringContent(jsonData, System.Text.Encoding.UTF8, "application/json");
                }
                var response = httpClient.SendAsync(request).Result;     //发送请求并获取响应
                response.EnsureSuccessStatusCode();     //确保请求成功
                var responseContent = response.Content.ReadAsStringAsync().Result;
                Dictionary<String, Object> resp = JsonConvert.DeserializeObject<Dictionary<String, Object>>(responseContent);
                return Resp.Success(resp);
            }
            catch (Exception ex)
            {
                return Resp.Fail("请求异常：" + ex.Message);
            }
        }
    }
}
